﻿using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Leo.Common.CAP
{
    public class CAPConfigurators
    {
        public static Action<CapOptions> Init(IConfiguration configuration, Action<CapOptions> action)
        {
            // 使用 自定义 配置文件
            if (configuration is null)
            {
                return action;
            }

            if (action is null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            // 使用默认配置文件 
            var capRabbitConfig = configuration.GetSection("CAPRabbitConfig");
            return (options) =>
            {
                options.UseMySql(configuration.GetConnectionString("MysqlConnection"));
                options.UseRabbitMQ(r =>
                {
                    r.HostName = capRabbitConfig["Host"];
                    r.UserName = capRabbitConfig["UserName"];
                    r.Password = capRabbitConfig["Password"];
                    r.Port = int.Parse(capRabbitConfig["Port"]);
                    r.VirtualHost = capRabbitConfig["VirtualHost"];
                });
            };
        }
    }
}
